/**
 * BrandBigData.com Inc.
 * Copyright (c) 2016 All Rights Reserved.
 */
package com.qibao.toolkit.protocol.protocols;

import com.qibao.toolkit.facade.exception.ServiceException;
import com.qibao.toolkit.protocol.facade.Request;
import com.qibao.toolkit.protocol.facade.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.http.HttpMethod;

import java.net.URISyntaxException;

/**
 * @author xumin
 * @version $Id:HttpGetProtocol.java, v0.1 2017/6/21 13:25 xumin
 */
public  class HttpProtocolTest extends HttpProtocol {

    public HttpProtocolTest(HttpMethod method) {
        super(method);
    }

    @Override
    protected Request preSendRequest(Request request) {
        return null;
    }

    @Override
    protected Response preReturnResponse(Response response) {
        return null;
    }

    @Override
    protected String prepareUrl(Request request) {
        if (HttpMethod.GET.equals(method) || (HttpMethod.POST.equals(method) && StringUtils.isEmpty(request.getRequestBody()))) {
            try {
                URIBuilder builder = new URIBuilder(request.getUrl());
                request.getQueryParameters().forEach((name, value) -> {
                    if (StringUtils.isEmpty(name) || null == value) {
                        return;
                    }
                    builder.addParameter(name, value);
                });
                return builder.build().toString();
            } catch (URISyntaxException e) {
                throw new ServiceException(e.getMessage(), e);
            }
        }
        return request.getUrl();
    }

    public static void main(String[] args) {
       HttpProtocolTest tr = new HttpProtocolTest(HttpMethod.POST);
        Request request = new Request();
        request.setUrl("http://www.baidu.com");
       tr.prepareUrl(request);
    }
}
